﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using PKURG.CostSplit.SyncManual.DAL;

namespace PKURG.CostSplit.SyncService.MING
{
    class SyncData
    {
       

        #region 明源楼栋数据
        string sqlString = @"select * ,case 分期 when '' then '一期' else 分期 end '项目期'
                            from 
                            ek_Company as A join
                            (
	                            select ProjGUID,ProjName,ProjShortName,BUGUID
	                            from p_Project
                            ) as B
                            on A.BUGUID=B.BUGUID
                            join
                            (
	                            select BldGUID,ProjGUID,AreaFullName as 分期,BldName as 楼栋名
	                            from p_building
                            ) as C
                            on B.ProjGUID=C.ProjGUID
                            join
                            (
	                            select BldGUID,
	                            sum(BldArea) as 建筑面积,
	                            sum(ScBldArea) as 实测建筑面积 ,
	                            sum(TnArea) as 套内面积,
	                            sum(ScTnArea) as 实测套内面积,
	                            sum(YsBldArea) as 预售建筑面积,
	                            sum(YsTnArea) as 预售套内面积
	                            --,sum(dspBldArea) as 待审批建筑面积,
	                            --sum(dspTnArea) as 待审批套内面积
	                            ,BProductTypeCode
	                            from p_room
	                            group by BldGUID,BProductTypeCode
                            ) as D
                            on C.BldGUID=D.BldGUID
                            join 
                            (
	                            select BuildProductTypeGUID,BProductTypeCode  
	                            from p_BuildProductType
                            ) as E
                            on E.BProductTypeCode=D.BProductTypeCode";
        #endregion

        private DataTable GetBaseData()
        {
            Founder.PKURG.DBUntility.DbHelperSQL sqlHelper = new Founder.PKURG.DBUntility.DbHelperSQL(PKURG.CostSplit.SyncManual.Properties.Settings.Default.MINGConnectonString);
            DataTable dt = sqlHelper.ExecuteDataTable(sqlString);
            return dt;
        }

        /// <summary>
        /// 同步楼栋数据
        /// </summary>
        /// <returns></returns>
        internal ReturnInfo SyncBuildingData()
        {
            CostSplitEntities context = new CostSplitEntities();
            Exception exeException = null;

            Guid mt = Guid.Empty;
            try
            {
                DataTable dt = GetBaseData();
                if (dt == null)
                {
                    return new ReturnInfo()
                    {
                        ex = new Exception("返回数据集不正确")
                    };
                }
               // LoggerWorker.logger.DebugFormat("MING：共获取到 {0}条数据", dt.Rows.Count);

                

                foreach (DataRow item in dt.Rows)
                {
                    Guid companyId = Guid.Parse(item["BUGUID"].ToString());
                    string companyName = item["BUName"].ToString();
                    M_Company company = context.M_Company.Where(x => x.Id == companyId).SingleOrDefault();
                    if (company == null)
                    {
                        company = new M_Company()
                        {
                            CompanyName = companyName,
                            Id = companyId
                        };
                        context.M_Company.AddObject(company);
                        
                    }
                    else
                    {
                        company.CompanyName = companyName;
                    }
                    
                    Guid projectID = Guid.Parse(item["ProjGUID"].ToString());
                    string projectName = item["ProjShortName"].ToString();
                    M_Project project = context.M_Project.Where(x => x.Id == projectID).SingleOrDefault();
                    if (project == null)
                    {
                        project = new M_Project()
                        {
                            ProjectName = projectName,
                            Id = projectID,
                            CompanyId = company.Id
                        };
                        mt = projectID;
                        context.M_Project.AddObject(project);
                    }
                    else if (projectName != project.ProjectName)
                    {
                        project.CompanyId = company.Id;
                        project.ProjectName = projectName;//更新项目名称
                    }

                    //项目期名称不能更改，否则同步出错
                    string projectStageName = item["项目期"].ToString();
                    M_ProjectStage projectstage = context.M_ProjectStage.Where(x => x.StageName == projectStageName && x.ProjectId == projectID).SingleOrDefault();
                    if (projectstage == null)
                    {
                        projectstage = new M_ProjectStage()
                        {
                            Id = Guid.NewGuid(),
                            StageName = projectStageName,
                            ProjectId = projectID
                        };
                        context.M_ProjectStage.AddObject(projectstage);
                    }



                    Guid buidingId = Guid.Parse(item["BldGUID"].ToString());
                    Guid typeID = Guid.Parse(item["BuildProductTypeGUID"].ToString());

                    M_Building buidingData = context.M_Building.Where(x => x.Id == buidingId &&x.ProductType==typeID).SingleOrDefault();
                    if (buidingData == null)
                    {
                        buidingData = new M_Building()
                        {
                            Id = buidingId,
                            Name = item["楼栋名"].ToString(),
                            ProductType = typeID,
                            StageID = projectstage.Id,
                            Area = GetDecData(item["建筑面积"]),
                            SCArea = GetDecData(item["实测建筑面积"]),
                            TNArea = GetDecData(item["套内面积"]),
                            SCTNArea = GetDecData(item["实测套内面积"]),
                            YSArea = GetDecData(item["预售建筑面积"]),
                            YSTNArea = GetDecData(item["预售套内面积"])
                        };
                        context.M_Building.AddObject(buidingData);
                    }
                    else
                    {
                        buidingData.Name = item["楼栋名"].ToString();
                        buidingData.Area = GetDecData(item["建筑面积"]);
                        buidingData.SCArea = GetDecData(item["实测建筑面积"]);
                        buidingData.TNArea = GetDecData(item["套内面积"]);
                        buidingData.SCTNArea = GetDecData(item["实测套内面积"]);
                        buidingData.YSArea = GetDecData(item["预售建筑面积"]);
                        buidingData.YSTNArea = GetDecData(item["预售套内面积"]);
                    }
                    context.SaveChanges();
                }
                
               

            }
            catch (Exception ex)
            {
                exeException = ex;
            }
            return new ReturnInfo()
            {
                ex = exeException
            };
        }
        
        private decimal? GetDecData(Object obj)
        {
            if (obj == null)
            {
                return 0;
            }
            if (string.IsNullOrEmpty(obj.ToString()))
            {
                return 0;
            }


            decimal value = 0;
            bool isDec = decimal.TryParse(obj.ToString(), out value);
            if (isDec)
            {
                return value;
            }
            return 0;
        }
    }
}
